package com.shejimoshi.单例模式.深浅克隆.深克隆.使用序列化进行深度复制;

import java.io.*;

public class CloneUtils {
    public static <T extends Serializable> T clone(T obj) {
        // 定义拷贝成功的对象
        T objClone = null;

        // 将拷贝对象转化为字节流并写入
        try {
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("obj"));
            out.writeObject(obj);
            out.flush();
            out.close();
        } catch (Exception e) {
            System.out.println("转化为二进制字节流失败：" + e.toString());
        }

        // 分配内存，将写入的二进制流转化成新的对象
        try {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream("obj"));
            objClone = (T) in.readObject();
            in.close();
        } catch (Exception e) {
            System.out.println("二进制转化为对象失败：" + e.toString());
        }

        return objClone;
    }
}
